from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from LogisticsCard.models import Package

@login_required
def package_list_view(request):
    packages = Package.objects.filter(delete_at__isnull=True)
    return render(request, 'package/index.html', {'packages': packages})

@login_required
def package_create_view(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description')
        price = request.POST.get('price')
        remark = request.POST.get('remark')
        Package.objects.create(name=name, description=description, price=price, remark=remark, delete_at=None)
        return redirect('/package/')
    return render(request, 'package/create.html')

@login_required
def package_edit_view(request, package_id):
    package = get_object_or_404(Package, id=package_id, delete_at__isnull=True)
    if request.method == 'POST':
        package.name = request.POST.get('name')
        package.description = request.POST.get('description')
        package.price = request.POST.get('price')
        package.remark = request.POST.get('remark')
        package.save()
        return redirect('/package/')
    return render(request, 'package/edit.html', {'package': package})

@login_required
def package_delete_view(request, package_id):
    from django.utils import timezone
    package = get_object_or_404(Package, id=package_id, delete_at__isnull=True)
    package.delete_at = timezone.now()
    package.save()
    return redirect('/package/')
